package network;

import java.io.IOException;
import java.net.*;


public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            DatagramPacket requestpacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestpacket);
            String request = new String(requestpacket.getData(), 0, requestpacket.getLength());
            String response = process(request);
            DatagramPacket responsepacket = new DatagramPacket(response.getBytes(), response.getBytes().length, requestpacket.getSocketAddress());
            socket.send(responsepacket);
            // 打印日志
            System.out.printf("[%s:%d] req: %s, resp: %s\n", requestpacket.getAddress().toString(),
                    requestpacket.getPort(), request, response);
        }
    }

    private String process(String request) {
        return request;
    }
    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
